<template>
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button style="float:right; margin-right: 30px" type="success" @click="dialogFormVisible=true">新增</el-button>

        <el-button style="float:right; margin-right: 30px" type="primary" @click="getUserList()">查询</el-button>
        <el-button style="float:right; margin-right: 15px" @click="handleResetSearch()">重置</el-button>
      </div>
      <!-- 文件上传窗口 -->
      <el-dialog v-model="uploadDialogVisible" title="上传文件" width="600px">
          <el-upload class="upload-demo" drag action="" :show-file-list="false" :before-upload="handleBeforeUpload"
            :on-change="handleFileChange">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">点击或拖拽文件到此区域进行上传</div>
          </el-upload>
          <el-table :data="uploadedData" empty-text="正在加载" v-if="uploadedData.length">
            <el-table-column prop="用户名" label="用户名" />
            <el-table-column prop="密码" label="密码" />
            <el-table-column prop="邮箱" label="邮箱" width="200" />
            <el-table-column prop="管理员" label="管理员" />
          </el-table>
          <template #footer>
            <el-button @click="uploadData">上传</el-button>
            <el-button @click="uploadDialogVisible = false">取 消</el-button>
          </template>
      </el-dialog>
      <!-- 新增窗口 -->
       <el-dialog v-model="addUserDialogVisible" title="新增用户" width="600px">
          <el-form>
            <el-form-item prop="email" label="用户邮箱：">
            <el-input v-model="updateForm.email" />
          </el-form-item>
          <el-form-item prop="username" label="用户名称：">
            <el-input v-model="updateForm.username" />
          </el-form-item>
          <!-- <el-form-item prop="email" label="设备编号：">
            <el-input v-model="updateForm.email" />
          </el-form-item> -->
          <el-form-item prop="isNotify" label="是否通知：">
            <el-input v-model="updateForm.isNotify" />
          </el-form-item>
          <el-form-item prop="isRoot" label="是否管理员：">
            <el-input v-model="updateForm.isRoot" />
          </el-form-item>
          </el-form>
          <el-button type="primary" style="margin-left: 50%;" @click="addConfirm()">提交</el-button>
       </el-dialog>
      <div style="margin-top: 30px; ">
        <el-form style="display: inline-block;">
          <div style="display: inline-block;margin-left:20px">
            <el-form-item label="用户名称：">
              <el-input class="input-width" placeholder="用户名称" v-model="queryParams.param.username" clearable></el-input>
            </el-form-item>
          </div>
          <div style="display: inline-block;margin-left:20px">
            <el-form-item label="邮箱：">
              <el-input class="input-width" placeholder="邮箱" v-model="queryParams.param.email" clearable></el-input>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </el-card>
    <el-table :data="usersList" style="width: 120%">
      <el-table-column prop="email" label="邮箱" width="200"/>
      <!-- <el-table-column prop="password" label="密码" /> -->
      <el-table-column prop="username" label="用户名" width="200"/>
      <el-table-column label="通知" width="200">
        <template v-slot="scope">
          <span>{{ scope.row.isNotify === 1 ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="管理员" width="200">
        <template v-slot="scope">
          <span>{{ scope.row.isRoot === 1 ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column  label="操作" width="200">
        <template #default="{ row }">
          <el-button
            size="small"
            type="primary"
            @click="() => handleUpdate(row)">编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="() => handleDelete(row.id)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 编辑框 -->
    <el-dialog v-model="dialogFormVisible" :before-close="handleBeforeClose" :title="updateForm.id ? '修改信息' : '新增信息'" width="800">
      <el-form ref="formRef" :model="updateForm" :rules="rules">
        <el-form-item prop="email" label="邮箱:">
          <el-input v-model="updateForm.email" />
        </el-form-item>
        <el-form-item prop="username" label="用户名称：">
          <el-input v-model="updateForm.username" />
        </el-form-item>
        <el-form-item prop="password" label="密码：">
          <el-input v-model="updateForm.password" />
        </el-form-item>
        <el-form-item prop="isNotify" label="是否通知:">
          <!-- <el-input v-model="updateForm.isNotify" /> -->
          <el-select placeholder="请选择" v-model="updateForm.isNotify" clearable>
            <el-option :label="'是'" :value="1"></el-option>
            <el-option :label="'否'" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="isRoot" label="是否管理员:">
          <!-- <el-input v-model="updateForm.isRoot" /> -->
          <el-select placeholder="请选择" v-model="updateForm.isRoot" clearable>
            <el-option :label="'是'" :value="1"></el-option>
            <el-option :label="'否'" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- <el-button type="primary" style="margin-left: 50%;" @click="confirm()">提交</el-button> -->
      <el-button type="primary" style="margin-left: 50%;" @click="confirm()">{{ updateForm.id ? '提交修改' : '提交新增' }}</el-button>
    </el-dialog>
  <div>
  <el-pagination
    :current-page="queryParams.pageNum"
    :page-size="queryParams.pageSize"
    :page-sizes="[15, 30, 45]"
    :small="false"
    :disabled="false"
    :background="true"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleNumChange"
  />
</div>
</template>
<script lang="ts" setup>
import { fetchUserList, updateUser, deleteUser,addUser } from '../../api/userAPi';
import { nextTick, ref, reactive, onMounted, VueElement} from 'vue';
import { ElMessage, ElMessageBox, } from "element-plus";

//获取列表数据
// 分页参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  param: {
    username:'',
    email:''
  }
});
let total = ref(0);
const usersList = ref([]); // 直接使用 ref 定义数组

function getUserList() {
 // console.log("00000001");
 // console.log(queryParams.value);
  fetchUserList(queryParams.value)
    .then(res => {
       console.log('res',res);
      // console.log("res.data.result.records",res.data.result);
      usersList.value = res.data.result.records; // 如果 res 是数组
       total.value = res.data.result.total;
      // console.log('queryParams.value',queryParams.param)
      //console.log('res',res)
    })
    .catch(error => {
      console.error("Error fetching users list:", error);
    });
}

const handleSizeChange = val => {
  queryParams.value.pageSize = val;
  getUserList();
};

const handleNumChange = val => {
  queryParams.value.pageNum = val;
  getUserList();
};

//编辑功能
const dialogFormVisible = ref(false);
const formRef = ref();

const updateForm = ref({
  id:"",
  email: "",
  username: "",
  isNotify: "",
  isRoot: "",
  password:""
});

const handleUpdate = (rowData = {}) => {
  dialogFormVisible.value = true;
  console.log("rowData", rowData);
  //弹窗打开form 声称是异步的
  nextTick(() => {
    //如果是编辑
    if (rowData) {
      Object.assign(updateForm.value, rowData);
      // updateForm.value = rowData
      console.log("这里是获取编辑数据", rowData);
    }
  });
};
const handleBeforeClose = (done) => {
  // 清空表单数据
  updateForm.value = {
    id:"",
    email: "",
    username: "",
    isNotify: "",
    isRoot: "",
    password:""
  };
  // 调用 done 方法关闭对话框
  done();
};
const confirm = async () => {
  console.log("更新内容", updateForm);
  console.log("更新内容", updateForm.value);
  if(updateForm.value.id==''){
    console.log("添加添加")
    addUser(updateForm.value)
    .then(response => {
      console.log('添加成功', response);
      dialogFormVisible.value = false; // 关闭弹窗
      ElMessage({
          message: "添加成功",
          type: "success",
          duration: 1000
        });
      // 可以根据需要进一步处理响应
      getUserList();
    })
    .catch(error => {
      console.error('添加失败', error);
      ElMessage({
        message: "添加失败",
        type: "error",
        duration: 1000
      });
    });
  }else{
     updateUser(updateForm.value)
    .then(response => {
      console.log('上传成功response', response);
      dialogFormVisible.value = false; // 关闭弹窗
      ElMessage({
          message: "修改成功",
          type: "success",
          duration: 1000
        });
      // 可以根据需要进一步处理响应
      getUserList();
    })
    .catch(error => {
      console.error('修改失败', error);
      ElMessage({
        message: "修改失败",
        type: "error",
        duration: 1000
      });
    });
  }
 
};

//删除
const handleDelete = async (id) => {
  try {
      await ElMessageBox.confirm('是否要该条数据', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
      console.log(id);
      await deleteUser(id);
      ElMessage({
        message: '删除成功',
        type: 'success',
        duration: 1000
      });
    } catch (error) {
    }
  getUserList();
};

//重置事件
const handleResetSearch = async () => {
  console.log(3189),
  queryParams.value.param.email = '',
  queryParams.value.param.username = '',
  getUserList()
}
//新增事件
const addUserDialogVisible = ref(false);
// const addConfirm = async() =>{
// //  addUserDialogVisible.value = true
//   if (updateForm.value.email==''){
//     console.log("添加添加")
//     addUser(updateForm.value)
//     .then(response => {
//       console.log('添加成功', response);
//       dialogFormVisible.value = false; // 关闭弹窗
//       ElMessage({
//           message: "添加成功",
//           type: "success",
//           duration: 1000
//         });
//       // 可以根据需要进一步处理响应
//       getUserList();
//     })
//     .catch(error => {
//       console.error('添加失败', error);
//       ElMessage({
//         message: "添加失败",
//         type: "error",
//         duration: 1000
//       });
//     });
//   }
//   else {
//     addUser(updateForm.value)
//     .then(response => {
//       console.log('上传成功', response);
//       dialogFormVisible.value = false; // 关闭弹窗
//       ElMessage({
//           message: "修改成功",
//           type: "success",
//           duration: 1000
//         });
//       // 可以根据需要进一步处理响应
//       getUserList();
//     })
//     .catch(error => {
//       console.error('修改失败', error);
//       ElMessage({
//         message: "修改失败",
//         type: "error",
//         duration: 1000
//       });
//     });
//   }
// }

onMounted(() => {
  getUserList();
});

</script>